package netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by yu756 on 2020/1/6 14:40
 * <p>
 * 需要继承一个HandlerAdapter
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Server ctx =" + ctx);
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送消息为：" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址：" + ctx.channel().remoteAddress());
        // 异步执行任务 TaskQueue
        // ctx.channel().eventLoop().execute(() -> {});
        // 异步执行调度任务 scheduleTaskQueue


    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 写入缓存并且刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello  客户端", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
